/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package audio.player;

/**
 *
 * @author głodoś
 */
import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * An example of playing a sound with an echo filter.
 *
 * @see EchoFilter
 * @see SimpleSoundPlayer
 */
public class LowPassFilter extends SoundFilter {

    //to do dupy nic tu nie dziala

    float phase;
   short lfoskip;
   long skipcount;
   float xn1, xn2, yn1, yn2;
   float b0, b1, b2, a0, a1, a2;

   float freq, startphase;
   float depth, freqofs, res;

    public LowPassFilter(int smoothing) {
        freq = 1.5f;
   startphase = 0;
   depth = 0.7f;
   freqofs = 0.3f;
   res = 2.5f;
   lfoskip = (short) (freq * 2 * Math.PI / 4000);
   skipcount = 0;
   xn1 = 0;
   xn2 = 0;
   yn1 = 0;
   yn2 = 0;
   b0 = 0;
   b1 = 0;
   b2 = 0;
   a0 = 0;
   a1 = 0;
   a2 = 0;


   phase = startphase;
    }

    /**
     * Gets the remaining size, in bytes, of samples that this filter can echo
     * after the sound is done playing. Ensures that the sound will have decayed
     * to below 1% of maximum volume (amplitude).
     */
    public synchronized int getRemainingSize() {
        return 0;
    }

    /**
     * Clears this EchoFilter's internal delay buffer.
     */
    public synchronized void reset() {
    }

    /**
     * Filters the sound samples to add an echo. The samples played are added to
     * the sound in the delay buffer multipied by the decay rate. The result is
     * then stored in the delay buffer, so multiple echoes are heard.
     */
    public synchronized void filter(byte[] samples, int offset, int length) {
        float frequency, omega, sn, cs, alpha;
        short in, out;


        for (int i = offset; i < offset+length; i+=2) {
            in = getSample(samples, i);

            if ((skipcount++) % 30 == 0) {
                frequency = (float) ((1 + Math.cos(skipcount * lfoskip + phase)) / 2);
                frequency = frequency * depth * (1 - freqofs) + freqofs;
                frequency = (float) Math.exp((frequency - 1) * 6);
                omega = (float) (Math.PI * frequency);
                sn = (float) Math.sin(omega);
                cs = (float) Math.cos(omega);
                alpha = sn / (2 * res);
                b0 = (1 - cs) / 2;
                b1 = 1 - cs;
                b2 = (1 - cs) / 2;
                a0 = 1 + alpha;
                a1 = -2 * cs;
                a2 = 1 - alpha;
            }
            out = (short) ((b0 * in + b1 * xn1 + b2 * xn2 - a1 * yn1 - a2 * yn2) / a0);
            xn2 = xn1;
            xn1 = in;
            yn2 = yn1;
            yn1 = out;

//      // Prevents clipping
//      if (out < -1)
//         out = -1;
//      else if (out> 1)
//         out = 1;

            setSample(samples, i, out);
        }
    }
}
